package com.example.libo.huihui.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.libo.huihui.R;
import com.example.libo.huihui.adapter.QingdanAdapter;
import com.example.libo.huihui.application.MyApplication;
import com.example.libo.huihui.been.QingdanEntity;
import com.example.libo.huihui.config.Urls;
import com.example.libo.huihui.databinding.FragmentQingdanBinding;
import com.example.libo.huihui.utils.HttpService;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class QingdanFragment extends Fragment implements Callback<QingdanEntity>, SwipeRefreshLayout.OnRefreshListener {
    private ArrayList datas = new ArrayList();
    private QingdanAdapter adapter;
    private FragmentQingdanBinding binding;
    private int page = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = DataBindingUtil.inflate(LayoutInflater.from(getContext()),R.layout.fragment_qingdan,container,false).getRoot();
        binding = DataBindingUtil.bind(view);
        initView();
        return view;
    }

    private void initView() {
        binding.rvQingdan.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new QingdanAdapter(getActivity(),datas);
        binding.rvQingdan.setAdapter(adapter);

        MyApplication.getHttpService().getQingdan(page++).enqueue(this);

        binding.srl.setOnRefreshListener(this);

        adapter.setLoadMore(new QingdanAdapter.IloadMore() {
            @Override
            public void loadMore() {
                MyApplication.getHttpService().getQingdan(page++).enqueue(QingdanFragment.this);
            }
        });
    }

    @Override
    public void onResponse(Call<QingdanEntity> call, Response<QingdanEntity> response) {
        binding.srl.setRefreshing(false);
        datas.addAll(response.body().getData());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<QingdanEntity> call, Throwable t) {

    }

    @Override
    public void onRefresh() {
        datas.clear();
        page = 0;
        MyApplication.getHttpService().getQingdan(page++).enqueue(this);
    }
}
